<?php

namespace App\Common;

use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * Excel处理类
 * */
class Excel
{


    /**
     * 获取excel文件内容
     * */
    public static function readExcel($filename, $columns, $startRow = 1): array
    {
        try {
            $fileParts = pathinfo($filename);
            $filetype = strtolower($fileParts['extension']);

            if ($filetype === 'xls') {
                $objReader = IOFactory::createReader('Xls');
            } elseif ($filetype === 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } elseif ($filetype === 'csv') {
                $objReader = IOFactory::createReader('Csv')
                    ->setDelimiter(',')
                    ->setInputEncoding('GBK') //处理csv读取中文异常问题
                    ->setEnclosure('"');
            } else {
                throw new \RuntimeException("不支持的文件类型");
            }

            $objReader->setReadDataOnly(true);

            $objPHPExcel = $objReader->load($filename);

            $objWorksheet = $objPHPExcel->getActiveSheet();  // 获取excel第一页

            $highestRow = $objWorksheet->getHighestRow(); // 获取总行数
            $excelResult = [];
            $i = 0;
            for ($j = $startRow; $j <= $highestRow; $j++) {
                foreach ($columns as $column => $index) {
                    $val = (string)$objWorksheet->getCell("$index$j")->getValue();
                    $excelResult[$i][$column] = trim($val);
                }
                $i++;
            }

            //删除表头
            unset($excelResult[0]);

            return $excelResult;
        } catch (\Exception $e) {
            throw new \RuntimeException($e->getMessage());
        }
    }


}